import Mn from 'backbone.marionette';
import ModalBehavior from '../../base/behaviors/ModalBehavior.js';
import {
    serializeForm,
    ajax_call,
    showLoader,
    hideLoader,
} from '../../tools.js';
import Radio from 'backbone.radio';
import {
    parseDate,
    dateToIso
} from '../../date.js';
import FileCollectionView from 'task/views/files/FileCollectionView.js';
import {
    FileRequirementView
} from 'task/views/files/FileRequirementView.js';
import PDFViewerView from "common/views/PDFViewerView";

import _ from 'underscore';

var template = require("./templates/StatusView.mustache");

const StatusView = Mn.View.extend({
    template: template,
    ui: {
        'textarea': 'textarea',
        btn_cancel: '.cancel',
        submit: 'button[name=submit]',
        form: 'form',
        force_file_validation: "input[name=force_file_validation]",
    },
    regions: {
        files: ".files",
        preview: {
            el: ".preview",
            replaceElement: true,
        },
    },
    behaviors: {
        modal: {
            behaviorClass: ModalBehavior
        }
    },
    // Event remonté par la FileCollectionView
    childViewEvents: {
        'file:updated': 'refreshFileRequirements',
    },
    events: {
        'click @ui.force_file_validation': "onForceFileValidationClick",
        'click @ui.btn_cancel': 'destroy',
        'click @ui.submit': 'onSubmit'
    },
    initialize: function (options) {
        this.facade = Radio.channel('facade');
        this.action = options.action;
        this.pdfUrl = window.location.pathname + ".pdf";
    },
    submitCallback(result) {},
    onForceFileValidationClick(event) {
        const checked = this.ui.force_file_validation.is(':checked');
        this.ui.submit.attr("disabled", !checked);
        this.ui.submit.attr("aria-disabled", !checked);
    },
    onSubmit(event, retryTime = 0) {
        event.preventDefault();
        let datas = serializeForm(this.getUI('form'));
        datas['submit'] = this.action.get('status');
        const url = this.action.get('url');
        showLoader();
        let timeout = 500;
        // Ici le global false nous permet d'intercepter 
        this.serverRequest = ajax_call(url, datas, "POST");
        this.serverRequest = this.serverRequest.fail((xhr) => {
            if (xhr.status == 423) {
                if (retryTime < 3) {
                    console.log("Retrying...");
                    setTimeout(() => this.onSubmit(event, retryTime + 1), timeout);
                    timeout *= 2;
                } else {
                    alert("Une erreur bloquante est survenue, veuillez réessayer ultérieurement.");
                    hideLoader();
                }
            }
        })
        this.serverRequest.then(
            this.submitCallback.bind(this)
        );
    },
    fileWarning() {
        const validation_status = this.action.get('status');
        let has_warning;
        if (validation_status != "invalid") {
            const collection = this.facade.request('get:collection', "file_requirements");
            if (collection) {
                has_warning = !collection.validate();
            }
        } else {
            has_warning = false;
        }
        return has_warning
    },
    dateWarning() {
        const validation_status = this.action.get('status');
        var result = {};
        console.log("validation_status : %s", validation_status);
        if (validation_status == 'valid') {
            let model = this.getOption('model');
            let date = model.get('date');
            let today = new Date();
            if ((date != dateToIso(today))) {
                result['ask_for_date'] = true;
                date = parseDate(date);
                result['date'] = date.toLocaleDateString();
                result['today'] = today.toLocaleDateString();
                result['has_error'] = true;
            }
        }
        return result;
    },
    cancelResultedInvoiceWarning() {
        const config = Radio.channel('config')
        return config.request('get:options', 'cancel_resulted_invoice', false);
    },
    templateContext() {
        const validation_status = this.action.get('status');
        let result = {
            ask_for_date: false,
            has_file_warning: this.fileWarning(),
            has_error: this.fileWarning(),
            cancel_resulted_invoice_warning: this.cancelResultedInvoiceWarning(),
        }
        _.extend(result, this.dateWarning());
        _.extend(result, this.action.attributes);
        if (validation_status == 'wait') {
            result['label'] = this.model.get('label') || "Demander la validation";
        } else {
            result['label'] = this.model.get('label') || "Enregistrer";
        }
        return result;
    },
    showPreview() {
        const view = new PDFViewerView({
            fileUrl: this.pdfUrl,
            title: "Prévisualisation",
        })
        this.showChildView('preview', view);

    },
    onRender() {
        console.log("Rendering Status View");
        if (this.fileWarning()) {
            const collection = this.facade.request('get:collection', 'file_requirements');
            const view = new FileCollectionView({
                collection: collection,
                childView: FileRequirementView
            });
            this.showChildView('files', view);
        }
        this.showPreview();
    },
    // Recharge la collection de requirement sur les fichiers et refait
    // le rendu de la popup
    refreshFileRequirements() {
        const collection = this.facade.request('get:collection', 'file_requirements');
        collection.fetch().then(() => this.render());
    }
});
export default StatusView;
